package com.jar.exercise.多线程.atomic.AtomicStampedReference;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 正常情况下 AtomicStampedReference<T> 的T应该是个业务对象，所以compareAndSet 才用==判断
 */
public class Main {
    private static Integer integer = 1000;
    private static final AtomicStampedReference<Integer> reference = new AtomicStampedReference<>(integer, 1);

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            int stamp = reference.getStamp();
            System.out.println(stamp);
            boolean isChange = reference.compareAndSet(integer, 2000, reference.getStamp(), reference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName()+":::>"+isChange);

            System.out.println(reference.getStamp());
            boolean isChange1 = reference.compareAndSet(2000, integer, reference.getStamp(), reference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName()+":::>"+isChange1);
            System.out.println(reference.getStamp());
        },"线程1");

        Thread thread2 = new Thread(() -> {
            int stamp = reference.getStamp();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean isChange1 = reference.compareAndSet(integer, 2000, stamp, stamp + 1);
            System.out.println(Thread.currentThread().getName()+":::>"+isChange1);
        },"线程2");
        thread1.start();
        thread2.start();
    }

}
